<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      html,
      body {
        margin: 0;
      }

    </style>
  </head>

  <body>
    <h1 id='start'>1.点击此处, 开始截屏</h1>
    <ul>
      <li>纯js调用, 无外部工具</li>
      <li>可以截取多屏幕/浏览器外部区域</li>
      <li>请授权, 允许共享屏幕</li>
    </ul>
    <div id="save-img">
      <button>2.点击保存为图片</button>
    </div>
    <div>截取图片结果:</div>
    <img id="img" style="width: 400px;" />
    <div></div>
    <div></div>
    <div></div>
    <div> 实时视频预览区域:</div>
    <script>
      let oCanvas = document.createElement('canvas');
      let oVideo = document.createElement('video');
      async function startCapture() {
        let videoStream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            frameRate: 60, // 帧率
            cursor: "always" //总是显示光标
          },
          logicalSurface: false, // 包含所选屏幕外区域
          audio: false // 不录制音频
        });

        // oVideo.style.display = 'none'; videoStream
        oVideo.style.cssText = 'width: 80vw;height: auto'
        oVideo.autoplay = 'true'
        oVideo.srcObject = videoStream
        document.body.appendChild(oVideo);
      }

      function screenshot() {
        setTimeout(() => {
          oCanvas.width = oVideo.videoWidth
          oCanvas.height = oVideo.videoHeight
          let p = oCanvas.getContext("2d");
          p.drawImage(oVideo, 0, 0, oVideo.videoWidth, oVideo.videoHeight);
          let imgURL = oCanvas.toDataURL("image/png");
          document.querySelector('#img').src = imgURL;
          let a = document.createElement('a')
          a.setAttribute('download', true)
          a.setAttribute('href', imgURL)
          a.click()
        }, 500)
      }
      document.querySelector('#start').addEventListener('click', startCapture);
      document.querySelector('#save-img').addEventListener('click', screenshot);
    </script>
  </body>

</html>
